
const searchPro = (citys,cityName) => {
  
  const cityMap = citys.reduce((o, cur) => {
    o[cur.text] = cur
    o[cur.code] = cur
    return o
  }, {}) 

  let res = cityMap[cityName]
  if (res) {
    return res
  }

  res = citys.filter((item) => item.text.includes(cityName))
  return res.length ? res[0] : {}
}

export const search = (s,citys) => {
/*   let s = ` 北京：起点 -- 太海路 -- 回南路 -- G15;





  河北：G18荣乌高速  --  冀津界；
  
  
  
  
  
  天津：S5津晋高速  --  宾水道  --  终点;` */

  if (!s) {
    console.log(`未输入内容`)
    return
  }

  s = s
    .replace(/(\s|\n)+/g, "")
    .replace(/(;|；)+$/g, "")
    .replace(/；/g, ";")
    .replace(/：/g, ":")

  const line = "-"

  const provinces = s.split(";")

  if (!provinces.length) {
    console.log(`;分割失败`)
    return
  }

  const list = []
  const provincesLen = provinces.length
  provinces.forEach((s, i) => {
    const [cityName, routeDesc] = s.split(":") || []
    if (!cityName) {
      console.log(`${s}省份未输入`)
      return
    }
    let { code, text, shortName } = searchPro(citys,cityName) || {}

    if (!code) {
      console.log(`${s}省份识别失败`)
      return
    }

    if (!routeDesc) {
      console.log(`${routeDesc}路线未输入`)
      return
    }

    let beginPoint = ""
    let route = ""
    let endPoint = ""
    if (provincesLen > 1) {
      if (i === 0) {
        const mached = routeDesc.split(line)
        beginPoint = mached ? mached[0] : ""
        route = beginPoint
          ? routeDesc.replace(new RegExp(`^${beginPoint}-+`, "g"), "")
          : routeDesc
      } else if (i === provinces.length - 1) {
        const mached = routeDesc.split(line)
        endPoint = mached ? mached[mached.length - 1] : ""
        route = endPoint
          ? routeDesc.replace(new RegExp(`-+${beginPoint}$`, "g"), "")
          : routeDesc
      } else {
        route = routeDesc
      }
    } else if (provincesLen === 1) {
      const mached = routeDesc.split(line)
      beginPoint = mached ? mached[0] : ""
      endPoint = mached ? mached[mached.length - 1] : ""

      route = beginPoint
        ? routeDesc.replace(new RegExp(`^${beginPoint}-+`, "g"), "")
        : routeDesc
      route = endPoint ? route.replace(new RegExp(`-+${beginPoint}$`, "g"), "") : route
    }

    list.push({
      distCode:code,
      text,
      shortName,
      beginPoint,
      endPoint,
      routeDesc: route.replace(new RegExp(`${line}+`, "mg"), line),
      _id: createId()
    })
  })


  return initAddS2E(list)
}

function initAddS2E(list=[]) { // 初始化添加数据时候更新省界
  const listLen = list.length
  list.forEach((item, index, arr) => {
    if (listLen > 1) {
      const { shortName } = item
      if (index === 0) {
        item.endPoint = shortName + arr[index + 1].shortName + "界"
      } else if (index === arr.length - 1) {
        item.beginPoint = shortName + arr[index - 1].shortName + "界"
      } else {
        item.beginPoint = shortName + arr[index - 1].shortName + "界"
        item.endPoint = shortName + arr[index + 1].shortName + "界"
      }
    }
  });
  return list
}
export function createId() {
  return Math.random().toFixed(20)
}

export function findRouteIndex(route, routes) {
  return routes.findIndex(item => { 
    return item._id === route._id
  })
}

export function addRoute(route, routes) {
  const index = findRouteIndex(route, routes)
  const prev = route
  const next = routes[index + 1]
  prev.endPoint = prev.shortName + "界"
  next.beginPoint = next.shortName + "界"
  routes.splice(index+1, 0, {
    code: "",
    text: "",
    shortName: "",
    beginPoint:'',
    endPoint: '',
    route: "",
    _id: createId()
  })
}

export function removeRoute(route, routes) {
  const index = findRouteIndex(route, routes)
  const isLast =index=== routes.length-1
  const prev = routes[index - 1]
  
  if (!isLast) {
    const next = routes[index + 1]
    prev.endPoint = prev.shortName + next.shortName + "界"
    next.beginPoint = next.shortName + prev.shortName + "界"
  } else { 
    prev.endPoint = ''
  }

  routes.splice(index, 1)
}

export function updateShortName(citys, route, routes) { 
  if (routes.length > 1) { 

    const index = findRouteIndex(route, routes)
    const prev = routes[index - 1]
    const next = routes[index + 1]
    let { shortName } = searchPro(citys,route.code ||route.text) || {}
  
      if (!shortName) {
        console.log(`${route.code ||route.text}省份识别失败`)
        return
    }
    let beginFlag, endFlag, prevFlag, nextFlag;
    if (index === 0) {
      endFlag = true;
      nextFlag = !!next;
    } else if (index === routes.length - 1) {
      beginFlag = true;
      prevFlag = !!prev;
    } else { 
      beginFlag = true;
      endFlag = true;
      prevFlag = true;
      nextFlag = true;
    }

   
    endFlag && (route.endPoint = shortName + (next ? next.shortName : '') + "界");
    beginFlag && (route.beginPoint = shortName + (prev ? prev.shortName : '') + "界");
    
    prevFlag && (prev.endPoint = prev.shortName + shortName + "界");
    nextFlag && (next.beginPoint = next.shortName + shortName + "界");
  }
}

export function historySearch(citys,routes) { 
  let list = []
  routes.forEach((item) => { 
    const { code ,text:originText} = item;
    let { text, shortName} = searchPro(citys,code ||originText) || {}
    if (!shortName) { 
      console.log(`${code || originText}省份未匹配到`);
      return;
    }

    list.push({ 
      ...item,
      // code、beginPoint、endPoint、route
      code,
      text,
      shortName,
      _id: createId()
    })

  })
  return initAddS2E(list)
}
